package de.reichelt.fxrequi;

import de.reichelt.fx.ComboBoxAddon;
import de.reichelt.fx.FXHelper;
import de.reichelt.fx.FxForm;
import de.reichelt.fx.FxOption;
import de.reichelt.fxrequi.data.Artefact;
import de.reichelt.fxrequi.data.DataStore;
import de.reichelt.fxrequi.data.Glossary;
import de.reichelt.fxrequi.data.Project;
import de.reichelt.fxrequi.data.ProjectVersion;
import de.reichelt.fxrequi.data.Role;
import de.reichelt.fxrequi.data.User;
import de.reichelt.fxrequi.data.UserRole;
import java.net.URL;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;

public class ProjectController implements Initializable {

  //<editor-fold defaultstate="collapsed" desc="Deklarationen der Controls">
  @FXML private HBox panNavigation;
  @FXML private Button btnNewProject;
  @FXML private Button btnEditProject;
  @FXML private Button btnShowRequirements;
  @FXML private MenuItem btnShowTestplan;
  @FXML private MenuItem btnShowTestruns;
  
  @FXML private TableView<Project> tableProjects;
  @FXML private TableColumn<Project, String> colName;
  @FXML private TableColumn<Project, String> colTitle;
  @FXML private TableColumn<Project, FxOption> colState;
  @FXML private TableColumn<Project, String> colDescr;
  
  @FXML private SplitPane panData;
  
  @FXML private AnchorPane panProject;
  @FXML private TextField txtName;
  @FXML private TextField txtTitle;
  @FXML private ComboBox<FxOption> cmbState;
  @FXML private TextArea txtDescr;
  @FXML private TextArea txtKeywords;
  @FXML private TextField txtDateCreated;
  @FXML private TextField txtUserCreated;
  
  @FXML private HBox panButtons;
  @FXML private Button btnCancel;
  @FXML private Button btnSave;
  
  @FXML private AnchorPane panExtra;
  
  @FXML private HBox panSubButtons;
  @FXML private Button btnSubNew;
  @FXML private Button btnSubEdit;
  @FXML private Button btnSubDelete;
  
  @FXML private Accordion accSubData;
  
  @FXML private TableView<UserRole> tableUserRoles;
  @FXML private TableColumn<UserRole, User> colUser;
  @FXML private TableColumn<UserRole, Role> colRole;
  
  @FXML private TableView<Artefact> tableArtefacts;
  @FXML private TableColumn<Artefact, String> colArtefact;
  
  @FXML private TableView<Glossary> tableGlossary;
  @FXML private TableColumn<Glossary, String> colGlossarName;
  @FXML private TableColumn<Glossary, String> colGlossarDescr;
  @FXML private TableColumn<Glossary, String> colGlossarSynonyms;
  
  @FXML private TableView<ProjectVersion> tableVersions;
  @FXML private TableColumn<ProjectVersion, String> colVersion;
  @FXML private TableColumn<ProjectVersion, String> colVersionDescr;
  //</editor-fold>
  
  private Logger log;
  private FxForm form;
  private FxForm formSub;
  private boolean isInsert = true;
  private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
  
  public ProjectController() {
    super();
    log = Logger.getLogger(this.getClass().getName());
  }
  
  @Override
  public void initialize(URL url, ResourceBundle rb) {
    log.fine("Initialisierung der Anzeige");
    try {
      FXrequi.BUSY = true;
      btnNewProject.setOnAction(this::newProjectAction);
      btnEditProject.setOnAction(this::editProjectAction);
      btnShowRequirements.setOnAction(this::showRequirementsAction);
      btnShowTestplan.setOnAction(this::showTestplanAction);
      btnShowTestruns.setOnAction(this::showTestrunsAction);
      
      //Projekte-Tabelle initialisieren
      DataStore ds = DataStore.getInstance();
      log.fine("fülle Tabellen Items");
      tableProjects.setItems(FXCollections.observableArrayList(ds.getProjects()));
      colName.setCellValueFactory(new PropertyValueFactory<>("name"));
      colTitle.setCellValueFactory(new PropertyValueFactory<>("title"));
      colState.setCellValueFactory(new PropertyValueFactory<>("state"));
      colDescr.setCellValueFactory(new PropertyValueFactory<>("descr"));
      tableProjects.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Project>() {
        @Override
        public void changed(ObservableValue<? extends Project> observable, Project oldValue, Project newValue) {
          log.fine("Projekttabelle selection changed: project="+newValue);
          if (!FXrequi.BUSY) {
            log.fine("wähle neues Projekt");
            FXrequi.APP.setSelectedProject(newValue);
            setData(newValue);
          }
        }
      });
      Platform.runLater(() -> tableProjects.requestFocus());
      
      //erzeuge Formular mit Feldern und Buttons
      form = new FxForm();
      form.registerButton(btnSave);
      form.registerField(txtName, "name", true, true);
      form.registerField(txtTitle, "title", true, true);
      cmbState.setItems(FXCollections.observableList(Project.states));
      new ComboBoxAddon(cmbState);
      form.registerField(cmbState, "state", true, true);
      form.registerField(txtDescr, "descr", true, true);
      form.registerField(txtDateCreated, "dateCreated", false, false);
      form.registerField(txtUserCreated, "userCreated", false, false);
      form.registerField(txtKeywords, "keywords", false, true);
      
      Project pro = FXrequi.APP.getSelectedProject();
      if (pro!=null) {
        tableProjects.getSelectionModel().select(pro);
        setData(pro);
      }
      
      btnSave.setOnAction(this::saveAction);
      btnCancel.setOnAction(this::cancelAction);
      
      btnSubNew.setOnAction(this::newSubdataAction);
      btnSubEdit.setOnAction(this::editSubdataAction);
      btnSubDelete.setOnAction(this::deleteSubdataAction);
      
      colVersion.setCellValueFactory(new PropertyValueFactory<>("name"));
      colVersionDescr.setCellValueFactory(new PropertyValueFactory<>("descr"));
      colUser.setCellValueFactory(new PropertyValueFactory<>("user"));
      colRole.setCellValueFactory(new PropertyValueFactory<>("role"));
      colArtefact.setCellValueFactory(new PropertyValueFactory<>("title"));
      colGlossarName.setCellValueFactory(new PropertyValueFactory<>("name"));
      colGlossarSynonyms.setCellValueFactory(new PropertyValueFactory<>("synonyms"));
      colGlossarDescr.setCellValueFactory(new PropertyValueFactory<>("descr"));
      
      accSubData.expandedPaneProperty().addListener(new ChangeListener<TitledPane>() {
        @Override
        public void changed(ObservableValue<? extends TitledPane> observable, TitledPane oldValue, TitledPane newValue) {
          setSubdata(newValue);
        }
      });
      FXrequi.BUSY = false;
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Erzeugen des Projekt-Dialogs!", ex);
      FXrequi.APP.showException("Fehler beim Erzeugen des Projekt-Dialogs!", ex);
    }
  }
  
  public void setData(Project data) {
    log.fine("aufgerufen: data="+data);
    try {
      isInsert = (data == null);
      panExtra.setDisable(isInsert);
      panButtons.setDisable(!isInsert);
      panProject.setDisable(!isInsert);
      panNavigation.setDisable(isInsert);
      txtName.setEditable(isInsert);
      if (isInsert) {
        form.clear();
      } else {
        txtName.setText(data.getName());
        txtTitle.setText(data.getTitle());
        cmbState.setValue(data.getState());
        txtDescr.setText(data.getDescr());
        txtDateCreated.setText(sdf.format(data.getDateCreated()));
        txtUserCreated.setText(data.getUserCreated());
        form.getField("keywords").setValue(data.getKeywords());
      }
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Füllen der Bedienelemente!", ex);
      FXrequi.APP.showException("Fehler beim Füllen der Bedienelemente!", ex);
    }
  }
  
  private void setSubdata(TitledPane pane) {
    try {
      panSubButtons.setDisable(pane==null);
      DataStore ds = DataStore.getInstance();
      if (pane!=null && pane.getText().equals("Mitglieder")) {
        log.fine("Subdaten gewählt, Mitglieder");
        tableUserRoles.setItems(ds.getUserRolesByProjectName(FXrequi.APP.getSelectedProject().getName()));
        
      } else if (pane!=null && pane.getText().equals("Versionen")) {
        log.fine("Subdaten gewählt, Versionen");
        tableVersions.setItems(ds.getVersionsByProjectName(FXrequi.APP.getSelectedProject().getName()));
        
      } else if (pane!=null && pane.getText().equals("Artefakte")) {
        log.fine("Subdaten gewählt, Artefakte");
        tableArtefacts.setItems(ds.getArtefactsByProjectName(FXrequi.APP.getSelectedProject().getName()));
        
      } else if (pane!=null && pane.getText().equals("Glossar")) {
        log.fine("Subdaten gewählt, Glossar");
        tableGlossary.setItems(ds.getGlossaryByProjectName(FXrequi.APP.getSelectedProject().getName()));
        
      }
    } catch (SQLException ex) {
      log.log(Level.SEVERE, "Fehler beim Füllen der Subdaten!", ex);
      FXrequi.APP.showException("Fehler beim Füllen der Subdaten!", ex);
    }
  }
  
  private void newProjectAction(ActionEvent event) {
    log.fine("aufgerufen");
    setData(null);
    panNavigation.setDisable(true);
    tableProjects.setDisable(true);
    panProject.setDisable(false);
    panButtons.setDisable(false);
    panExtra.setDisable(true);
  }
  
  private void editProjectAction(ActionEvent event) {
    log.fine("aufgerufen");
    panNavigation.setDisable(true);
    tableProjects.setDisable(true);
    panProject.setDisable(false);
    panButtons.setDisable(false);
    panExtra.setDisable(true);
  }
  
  private void cancelAction(ActionEvent event) {
    log.fine("aufgerufen");
    form.resetErrors();
    setData(FXrequi.APP.getSelectedProject());
    panNavigation.setDisable(false);
    tableProjects.setDisable(false);
    panProject.setDisable(true);
    panButtons.setDisable(true);
    panExtra.setDisable(false);
  }

  private void saveAction(ActionEvent event) {
    log.fine("aufgerufen");
    try {
      form.resetErrors();
      if (!form.validate()) {
        return;
      }
      DataStore ds = DataStore.getInstance();
      if (isInsert) {
        Date dateCreated = new Date();
        User user = ds.getLoginUser();
        String username = user.getName();
        Project pro = new Project((String) form.getField("name").getValue(),
              (String) form.getField("title").getValue(),
              (FxOption) form.getField("state").getValue(),
              (String) form.getField("descr").getValue(),
              dateCreated, username,
              (String) form.getField("keywords").getValue()  );
        ds.insertProject(pro);
        tableProjects.setItems(FXCollections.observableArrayList(ds.getProjects()));
        tableProjects.getSelectionModel().select(pro);
      } else {
        Project pro = tableProjects.getSelectionModel().getSelectedItem();
        pro.setTitle((String)form.getField("title").getValue());
        pro.setState((FxOption)form.getField("state").getValue());
        pro.setDescr((String)form.getField("descr").getValue());
        pro.setKeywords((String)form.getField("keywords").getValue());
        ds.updateProject(pro);
      }
      panNavigation.setDisable(false);
      tableProjects.setDisable(false);
      panProject.setDisable(true);
      panButtons.setDisable(true);
      panExtra.setDisable(false);
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Prüfen und Speichern des Projekts!", ex);
      FXrequi.APP.showException("Fehler beim Prüfen und Speichern des Projekts!", ex);
    }
  }
  
  private void newSubdataAction(ActionEvent event) {
    try {
      DialogWindow dlg = new DialogWindow("Anforderungsverwaltung", null);
      dlg.setHeight(200);
      dlg.setWidth(400);
      dlg.setResizable(false);
      switch (accSubData.getExpandedPane().getText()) {
        case "Mitglieder":
          generateUserRoleForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            UserRole role = (UserRole)dlg.getData();
            DataStore ds = DataStore.getInstance();
            ds.insertUserRole(role);
            tableUserRoles.getItems().add(role);
            tableUserRoles.getSelectionModel().select(role);
          }
          break;
        case "Versionen":
          generateVersionForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            ProjectVersion version = (ProjectVersion)dlg.getData();
            DataStore ds = DataStore.getInstance();
            version.setUserCreated(ds.getLoginUser().getName());
            ds.insertProjectVersion(version);
            tableVersions.getItems().add(version);
            tableVersions.getSelectionModel().select(version);
          }
          break;
        case "Artefakte":
          generateArtefactsForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            Artefact artefact = (Artefact)dlg.getData();
            DataStore ds = DataStore.getInstance();
            artefact.setUserCreated(ds.getLoginUser().getName());
            ds.insertArtefact(artefact);
            tableArtefacts.getItems().add(artefact);
            tableArtefacts.getSelectionModel().select(artefact);
          }
          break;
        case "Glossar":
          generateGlossaryForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            Glossary glossary = (Glossary)dlg.getData();
            DataStore ds = DataStore.getInstance();
            glossary.setUserCreated(ds.getLoginUser().getName());
            ds.insertGlossary(glossary);
            tableGlossary.getItems().add(glossary);
            tableGlossary.getSelectionModel().select(glossary);
          }
          break;
      }
      
      
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Aufruf des Dialogs!", ex);
      FXrequi.APP.showException("Fehler beim Aufruf des Dialogs!", ex);
    }
  }

  private void editSubdataAction(ActionEvent event) {
    try {
      DialogWindow dlg = new DialogWindow("Anforderungsverwaltung", null);
      dlg.setHeight(200);
      dlg.setWidth(400);
      dlg.setResizable(false);
      switch (accSubData.getExpandedPane().getText()) {
        case "Mitglieder":
          UserRole role = tableUserRoles.getSelectionModel().getSelectedItem();
          if (role==null) {
            FXrequi.APP.showError("Bitte wählen Sie zuerst ein Mitglied aus.");
            return;
          }
          dlg.setData(role);
          generateUserRoleForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            role = (UserRole)dlg.getData();
            DataStore ds = DataStore.getInstance();
            ds.updateUserRole(role);
          }
          break;
        case "Versionen":
          ProjectVersion version = tableVersions.getSelectionModel().getSelectedItem();
          if (version==null) {
            FXrequi.APP.showError("Bitte wählen Sie zuerst eine Version aus.");
            return;
          }
          dlg.setData(version);
          generateVersionForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            version = (ProjectVersion)dlg.getData();
            DataStore ds = DataStore.getInstance();
            ds.updateProjectVersion(version);
          }
          break;
        case "Artefakte":
          Artefact artefact = tableArtefacts.getSelectionModel().getSelectedItem();
          if (artefact==null) {
            FXrequi.APP.showError("Bitte wählen Sie zuerst ein Artefakt aus.");
            return;
          }
          dlg.setData(artefact);
          generateArtefactsForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            artefact = (Artefact)dlg.getData();
            DataStore ds = DataStore.getInstance();
            ds.updateArtefact(artefact);
          }
          break;
        case "Glossar":
          Glossary glossary = tableGlossary.getSelectionModel().getSelectedItem();
          if (glossary==null) {
            FXrequi.APP.showError("Bitte wählen Sie zuerst einen Glossareintrag aus.");
            return;
          }
          dlg.setData(glossary);
          generateGlossaryForm(dlg);
          dlg.showAndWait();
          if (dlg.getResult()==dlg.RESULT_OK) {
            glossary = (Glossary)dlg.getData();
            DataStore ds = DataStore.getInstance();
            ds.updateGlossary(glossary);
          }
          break;
      }
      
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Aufruf des Dialogs!", ex);
      FXrequi.APP.showException("Fehler beim Aufruf des Dialogs!", ex);
    }
  }

  private void deleteSubdataAction(ActionEvent event) {
    switch (accSubData.getExpandedPane().getText()) {
        case "Mitglieder":
          break;
        case "Versionen":
          break;
        case "Artefakte":
          break;
        case "Glossar":
          break;
      }
  }

  private void generateVersionForm(DialogWindow dlg) {
    ProjectVersion obj = (ProjectVersion)dlg.getData();
    AnchorPane pane = dlg.getPane();
    pane.getStylesheets().add("/de/reichelt/fxrequi/fxrequi.css");
    
    Label laTitle = new Label(obj==null?"Version erfassen":"Version ändern");
    laTitle.setAlignment(Pos.CENTER);
    laTitle.setStyle("-fx-font-size:18;");
    FXHelper.add2AnchorPane(pane, laTitle, 5.0, 5.0, 5.0, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Version:"), 5.0, 35.0, null, null);
    TextField txName = new TextField(obj==null?"":obj.getName());
    txName.setPrefSize(200,26);
    FXHelper.add2AnchorPane(pane, txName, 100.0, 35.0, null, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Beschreibung:"), 5.0, 65.0, null, null);
    TextArea txDescr = new TextArea(obj==null?"":obj.getDescr());
    txDescr.setWrapText(true);
    FXHelper.add2AnchorPane(pane, txDescr, 100.0, 65.0, 10.0, 35.0);
    
    Button btSave = new Button("speichern");
    btSave.setDefaultButton(true);
    FXHelper.add2AnchorPane(pane, btSave, 10.0, null, null, 5.0);
    Button btCancel = new Button("abbrechen");
    btCancel.setCancelButton(true);
    FXHelper.add2AnchorPane(pane, btCancel, 100.0, null, null, 5.0);
    formSub = new FxForm();
    formSub.registerButton(btSave);
    formSub.registerField(txName, "name", true, true);
    formSub.registerField(txDescr, "descr", true, true);
    btCancel.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        formSub.resetErrors();
        if (dlg.result==dlg.RESULT_UNDEFINED) {
          dlg.setResult(dlg.RESULT_CANCELLED);
        }
        dlg.close();
      }
    });
    btSave.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        try {
          formSub.resetErrors();
          if (formSub.validate()) {
            ProjectVersion ver = (ProjectVersion)dlg.getData();
            if (ver==null) {
              ver = new ProjectVersion();
            }
            ver.setProjectName(FXrequi.APP.getSelectedProject().getName());
            ver.setName((String)formSub.getField("name").getValue());
            ver.setDescr((String)formSub.getField("descr").getValue());
            dlg.setData(ver);
            dlg.setResult(dlg.RESULT_OK);
            dlg.close();
          }
        } catch (Exception ex) {
          log.log(Level.SEVERE, "Fehler beim Prüfen der Projektversion!", ex);
          FXrequi.APP.showException("Fehler beim Prüfen der Projektversion!", ex);
        }
      }
    });
  }

  private void generateUserRoleForm(DialogWindow dlg) throws Exception {
    UserRole obj = (UserRole)dlg.getData();
    DataStore ds = DataStore.getInstance();
    AnchorPane pane = dlg.getPane();
    pane.getStylesheets().add("/de/reichelt/fxrequi/fxrequi.css");
    
    Label laTitle = new Label(obj==null?"Benutzerrolle erfassen":"Benutzerrolle ändern");
    laTitle.setAlignment(Pos.CENTER);
    laTitle.setStyle("-fx-font-size:18;");
    FXHelper.add2AnchorPane(pane, laTitle, 5.0, 5.0, 5.0, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Benutzer:"), 5.0, 35.0, null, null);
    ComboBox<User> cmbUser = new ComboBox<>(FXCollections.observableArrayList(ds.getUsers()));
    if (obj!=null) {
      cmbUser.getSelectionModel().select(obj.getUser());
    }
    cmbUser.setPrefSize(200,26);
    FXHelper.add2AnchorPane(pane, cmbUser, 100.0, 35.0, null, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Rolle:"), 5.0, 65.0, null, null);
    ComboBox<Role> cmbRole = new ComboBox(FXCollections.observableArrayList(ds.getRoles()));
    if (obj!=null) {
      cmbRole.getSelectionModel().select(obj.getRole());
    }
    cmbRole.setPrefSize(200,26);
    FXHelper.add2AnchorPane(pane, cmbRole, 100.0, 65.0, null, null);
    
    Button btSave = new Button("speichern");
    btSave.setDefaultButton(true);
    FXHelper.add2AnchorPane(pane, btSave, 10.0, null, null, 5.0);
    Button btCancel = new Button("abbrechen");
    btCancel.setCancelButton(true);
    FXHelper.add2AnchorPane(pane, btCancel, 100.0, null, null, 5.0);
    formSub = new FxForm();
    formSub.registerButton(btSave);
    formSub.registerField(cmbUser, "user", true, true);
    formSub.registerField(cmbRole, "role", true, true);
    btCancel.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        formSub.resetErrors();
        if (dlg.result==dlg.RESULT_UNDEFINED) {
          dlg.setResult(dlg.RESULT_CANCELLED);
        }
        dlg.close();
      }
    });
    btSave.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        try {
          formSub.resetErrors();
          if (formSub.validate()) {
            UserRole role = (UserRole)dlg.getData();
            if (role==null) {
              role = new UserRole();
            }
            role.setProject(FXrequi.APP.getSelectedProject());
            role.setUser((User)formSub.getField("user").getValue());
            role.setRole((Role)formSub.getField("role").getValue());
            dlg.setData(role);
            dlg.setResult(dlg.RESULT_OK);
            dlg.close();
          }
        } catch (Exception ex) {
          log.log(Level.SEVERE, "Fehler beim Prüfen der Benutzerrollen!", ex);
          FXrequi.APP.showException("Fehler beim Prüfen der Benutzerrollen!", ex);
        }
      }
    });
  }

  private void generateArtefactsForm(DialogWindow dlg) throws Exception {
    Artefact obj = (Artefact)dlg.getData();
    AnchorPane pane = dlg.getPane();
    pane.getStylesheets().add("/de/reichelt/fxrequi/fxrequi.css");
    
    Label laTitle = new Label(obj==null?"Artefakt erfassen":"Artefakt ändern");
    laTitle.setAlignment(Pos.CENTER);
    laTitle.setStyle("-fx-font-size:18;");
    FXHelper.add2AnchorPane(pane, laTitle, 5.0, 5.0, 5.0, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Name:"), 5.0, 35.0, null, null);
    TextField txTitle = new TextField(obj==null?"":obj.getTitle());
    txTitle.setPrefSize(250,26);
    FXHelper.add2AnchorPane(pane, txTitle, 100.0, 35.0, null, null);
    
    Button btSave = new Button("speichern");
    btSave.setDefaultButton(true);
    FXHelper.add2AnchorPane(pane, btSave, 10.0, null, null, 5.0);
    Button btCancel = new Button("abbrechen");
    btCancel.setCancelButton(true);
    FXHelper.add2AnchorPane(pane, btCancel, 100.0, null, null, 5.0);
    formSub = new FxForm();
    formSub.registerButton(btSave);
    formSub.registerField(txTitle, "title", true, true);
    btCancel.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        formSub.resetErrors();
        if (dlg.result==dlg.RESULT_UNDEFINED) {
          dlg.setResult(dlg.RESULT_CANCELLED);
        }
        dlg.close();
      }
    });
    btSave.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        try {
          formSub.resetErrors();
          if (formSub.validate()) {
            Artefact art = (Artefact)dlg.getData();
            if (art==null) {
              art = new Artefact();
            }
            art.setProjectName(FXrequi.APP.getSelectedProject().getName());
            art.setTitle((String)formSub.getField("title").getValue());
            dlg.setData(art);
            dlg.setResult(dlg.RESULT_OK);
            dlg.close();
          }
        } catch (Exception ex) {
          log.log(Level.SEVERE, "Fehler beim Prüfen der Benutzerrollen!", ex);
          FXrequi.APP.showException("Fehler beim Prüfen der Benutzerrollen!", ex);
        }
      }
    });
  }

  private void generateGlossaryForm(DialogWindow dlg) {
    Glossary obj = (Glossary)dlg.getData();
    AnchorPane pane = dlg.getPane();
    pane.getStylesheets().add("/de/reichelt/fxrequi/fxrequi.css");
    
    Label laTitle = new Label(obj==null?"Glossareintrag erfassen":"Glossareintrag ändern");
    laTitle.setAlignment(Pos.CENTER);
    laTitle.setStyle("-fx-font-size:18;");
    FXHelper.add2AnchorPane(pane, laTitle, 5.0, 5.0, 5.0, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Begriff:"), 5.0, 35.0, null, null);
    TextField txName = new TextField(obj==null?"":obj.getName());
    txName.setPrefSize(200,26);
    FXHelper.add2AnchorPane(pane, txName, 100.0, 35.0, null, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Synonyme:"), 5.0, 65.0, null, null);
    TextField txSynonyms = new TextField(obj==null?"":obj.getSynonyms());
    txSynonyms.setPrefSize(200,26);
    FXHelper.add2AnchorPane(pane, txSynonyms, 100.0, 65.0, 10.0, null);
    
    FXHelper.add2AnchorPane(pane, new Label("Beschreibung:"), 5.0, 95.0, null, null);
    TextArea txDescr = new TextArea(obj==null?"":obj.getDescr());
    txDescr.setWrapText(true);
    FXHelper.add2AnchorPane(pane, txDescr, 100.0, 95.0, 10.0, 35.0);
    
    Button btSave = new Button("speichern");
    btSave.setDefaultButton(true);
    FXHelper.add2AnchorPane(pane, btSave, 10.0, null, null, 5.0);
    Button btCancel = new Button("abbrechen");
    btCancel.setCancelButton(true);
    FXHelper.add2AnchorPane(pane, btCancel, 100.0, null, null, 5.0);
    formSub = new FxForm();
    formSub.registerButton(btSave);
    formSub.registerField(txName, "name", true, true);
    formSub.registerField(txSynonyms, "synonyms", false, true);
    formSub.registerField(txDescr, "descr", true, true);
    btCancel.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        formSub.resetErrors();
        if (dlg.result==dlg.RESULT_UNDEFINED) {
          dlg.setResult(dlg.RESULT_CANCELLED);
        }
        dlg.close();
      }
    });
    btSave.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent event) {
        log.fine("aufgerufen");
        try {
          formSub.resetErrors();
          if (formSub.validate()) {
            Glossary glossary = (Glossary)dlg.getData();
            if (glossary==null) {
              glossary = new Glossary();
            }
            glossary.setProjectName(FXrequi.APP.getSelectedProject().getName());
            glossary.setName((String)formSub.getField("name").getValue());
            glossary.setSynonyms((String)formSub.getField("synonyms").getValue());
            glossary.setDescr((String)formSub.getField("descr").getValue());
            dlg.setData(glossary);
            dlg.setResult(dlg.RESULT_OK);
            dlg.close();
          }
        } catch (Exception ex) {
          log.log(Level.SEVERE, "Fehler beim Prüfen der Projektversion!", ex);
          FXrequi.APP.showException("Fehler beim Prüfen der Projektversion!", ex);
        }
      }
    });
  }

  private void showRequirementsAction(ActionEvent event) {
    try {
      Project pro = FXrequi.APP.getSelectedProject();
      FXrequi.APP.setTopPane(FXrequi.APP.getProjectHeader(pro,"Anforderungen"));
      FXMLLoader ldr = new FXMLLoader(this.getClass().getResource("RequirementView.fxml"));
      BorderPane pane = (BorderPane)ldr.load();
      FXrequi.APP.setMainPane(pane);
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Erzeugen der Anforderungsansicht!", ex);
      FXrequi.APP.showException("Fehler beim Erzeugen der Anforderungsansicht!", ex);
    }
  }
  
  private void showTestplanAction(ActionEvent event) {
    try {
      Project pro = FXrequi.APP.getSelectedProject();
      FXrequi.APP.setTopPane(FXrequi.APP.getProjectHeader(pro,"Testplan"));
      FXMLLoader ldr = new FXMLLoader(this.getClass().getResource("TestplanView.fxml"));
      AnchorPane pane = (AnchorPane)ldr.load();
      FXrequi.APP.setMainPane(pane);
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Erzeugen der Testplanansicht!", ex);
      FXrequi.APP.showException("Fehler beim Erzeugen der Testplanansicht!", ex);
    }
  }
  
  private void showTestrunsAction(ActionEvent event) {
    //TODO Testläufe anzeigen
    try {
      Project pro = FXrequi.APP.getSelectedProject();
      FXrequi.APP.setTopPane(FXrequi.APP.getProjectHeader(pro,"Testläufe"));
      FXMLLoader ldr = new FXMLLoader(this.getClass().getResource("TestrunsView.fxml"));
      BorderPane pane = (BorderPane)ldr.load();
      FXrequi.APP.setMainPane(pane);
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Fehler beim Erzeugen der Testlaufansicht!", ex);
      FXrequi.APP.showException("Fehler beim Erzeugen der Testlaufansicht!", ex);
    }
  }
  

}
